<?php

defined('SYSPATH') or die('No direct script access.');

class Ads_Cian extends Ads implements Ads_Interface {

	public function __construct($config) {
		parent::__construct($config);
		$this->_typeid = Arr::get($this->_config, 'typeid', null);
		if (empty($this->_typeid)) {
			throw new Ads_Exception('No Ads typeid defined in configuration');
		}
		$this->_database = Arr::get($this->_config, 'database', null);
		if (empty($this->_database)) {
			throw new Ads_Exception('No Ads database defined in configuration');
		}
		$this->_livetime = Arr::get($this->_config, 'livetime', null);
		if (empty($this->_livetime)) {
			throw new Ads_Exception('No Ads livetime defined in configuration');
		}
		if (class_exists('phpQuery')===FALSE) {
			throw new Ads_Exception('"phpQuery" requires');
		}
		return;
	}

	public function parse($html = '') {
		if (empty($html)) {
			$html = &$this->_data;
		}
		$document = phpQuery::newDocument($html);
		$rows = pq("table.cat tr[id^='tr_']");
		foreach ($rows as $row) {
			pq($row)->find("br")->replaceWith(" ");
			pq($row)->find("div.complaint")->replaceWith("");
			pq($row)->find("span.np")->replaceWith("");
			$id = str_replace('tr_', '', pq($row)->attr('id'));
			$data[$id]['distance'] = pq($row)->find("td[id$='_metro']")->clone()->children()->remove()->end()->text();
			for ($i = 0; $i < pq($row)->find("td[id$='_metro'] a")->length; $i++) {
				$_text = pq($row)->find("td[id$='_metro'] a")->eq($i)->text();
				$_href = str_replace('/cat.php?deal_type=1&', '', pq($row)->find("td[id$='_metro'] a")->eq($i)->attr('href'));
				if (preg_match('`^obl_id=(\d+)$`si', $_href)) {
					$data[$id]['city'] = $_text;
				}
				elseif (preg_match('`^obl_id=(\d+)&street\[0\]=(\d+)$`si', $_href)) {
					$data[$id]['street'] = $_text;
				}
				elseif (preg_match('`^obl_id=(\d+)&street\[0\]=(\d+)&house=(\d+)&ohn=(\d+)$`si', $_href)) {
					$data[$id]['house'] = $_text;
				}
				elseif (preg_match('`^obl_id=(\d+)&metro\[0\]=(\d+)$`si', $_href,$m)) {
					$data[$id]['metro'] = $_text;
					$data[$id]['mid'] = $m[2];
				}
			}
			$data[$id]['room'] = pq($row)->find("td[id$='_room'] a")->text();
			$data[$id]['rooms'] = pq($row)->find("td[id$='_rooms']")->text();
			$data[$id]['price'] = pq($row)->find("td[id$='_price']")->text();
			$data[$id]['floor'] = pq($row)->find("td[id$='_floor']")->text();
			$data[$id]['dopsved'] = pq($row)->find("td[id$='_dopsved']")->text();
			$data[$id]['com'] = pq($row)->find("td[id$='_com']")->text();
			$data[$id]['contacts'] = implode(',', preg_split("/[\s]+/", UTF8::trim(pq($row)->find("td[id$='_contacts'] a")->text())));
			$data[$id]['datetime'] = pq($row)->find("td[id$='_comment'] span[id^='added_']")->text();
			$data[$id]['comment'] = pq($row)->find("td[id$='_comment']")->clone()->children()->remove()->end()->text();
			$data[$id]['url'] = 'http://www.cian.ru' . pq($row)->find("td[id$='_comment'] a[href^='/rent/flat/']")->eq(0)->attr('href');
			$data[$id]['added'] = time();
			$data[$id]['rent'] = 0;
			if (UTF8::strpos($data[$id]['price'], 'сутки') !== FALSE) {
				$data[$id]['rent'] = 1;
			}
		}
		foreach ($data as $id => &$arr) {
			foreach ($arr as $field => &$str) {
				if ($field != 'contacts') {
					$str = preg_replace('"\s+"si', ' ', UTF8::trim(str_replace('&nbsp;', ' ', $str)));
				}
			}
		}
		return $data;
	}

	public function write($data) {
		$time = time();
		try {
			$db = Database::instance($this->_database);
			$prefix = $db->table_prefix();
			foreach ($data as $adsid => &$arr) {
				foreach ($arr as $field => &$value) {
					$vals[] = '(' . $this->_typeid . ', ' . $adsid . ', ' . $db->escape($field) . ', ' . $db->escape($value) . ')';
					$times[] = '(' . $adsid . ',' . $time . ')';
				}
			}if (!empty($vals)) {
				DB::query(Database::INSERT, 'REPLACE INTO ' . $prefix . 'ads VALUES ' . implode(',', $vals))->execute($this->_database);
			}
			if (!empty($times)) {
				DB::query(Database::INSERT, 'REPLACE INTO ' . $prefix . 'adsts VALUES ' . implode(',', $times))->execute($this->_database);
			}
			$sub = DB::select('adsid')->from('adsts')->where('timestamp', '<', $time-$this->_livetime);
			DB::delete('ads')->where('adsid', 'IN', $sub)->execute($this->_database);
			DB::delete('adsts')->where('timestamp', '<', $time-$this->_livetime)->execute($this->_database);
		}
		catch (Database_Exception $e) {
			echo $e->getMessage();
		}
	}

		public function readnew($limit = 20) {
		unset($this->_ads);
		$db = Database::instance($this->_database);
		$_adsids = DB::select('adsid')->from('adsts')->order_by('timestamp', 'DESC')->limit($limit)->execute($this->_database)->as_array();

		foreach($_adsids as &$adsid){
			$this->_adslist[$adsid['adsid']] = $this->read($adsid['adsid'])->as_array();
		}
		return $this->_adslist;
	}

	public function read($adsid) {
		unset($this->_ads);
		$db = Database::instance($this->_database);
		$_ads = DB::select('field','value')->from('ads')->where('typeid', '=', $this->_typeid)->and_where('adsid', '=', $adsid)->execute($this->_database)->as_array();
		foreach($_ads as &$arr){
			$this->_ads[$arr['field']] = $arr['value'];
		}
		return $this;
	}

	public function as_array() {
		return $this->_ads;
	}

	public function get($key,$default = NULL) {
		if (Arr::get($this->_ads, $key, $default)==NULL){
			throw new Ads_Exception('No field in Ads: "'.$key.'"');
		}
		else {
			return Arr::get($this->_ads, $key, $default);
		}
	}

	public function count() {
		$db = Database::instance($this->_database);
		return DB::select(array(DB::expr('COUNT(*)'), 'count'))->from('adsts')->execute($this->_database)->get('count', 0);
	}
	/*public function query($url, $cache = FALSE) {

	$url_parts=parse_url($url);
	parse_str($url_parts['query'], $get_array);
	$url=$url_parts['scheme'].'://'.$url_parts['host'].$url_parts['path'];
		$request = Request::factory($url)
		->query($get_array)
				->method(Request::GET);
		$request->client()
				->options(array(
					CURLOPT_SSL_VERIFYPEER => FALSE,
					CURLOPT_USERAGENT => empty(Request::$user_agent)?Request::$user_agent:'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36',
					CURLOPT_HTTPHEADER => array(
						'Accept-Encoding:gzip,deflate,sdch',
						'Accept-Language:ru-RU,ru;q=0.8,en-US;q=0.6,en;q=0.4',
					),
					CURLOPT_FOLLOWLOCATION => TRUE,
					CURLOPT_COOKIEFILE => APPPATH . "config/cookie.file",
					CURLOPT_COOKIEJAR => APPPATH . "config/cookie.file",
		));
		$response = $request->execute();
		$data = $response->body();

		$this->_data = $data;
		return $this;
	}*/

}
